import Loading from 'Comps/Loading/Handdraw'
import Effect from 'Comps/Effect'
import { mapGetters } from 'vuex'
import { isPc, isMobile, getViewport, getIP, getPlatform, DeepCloneData, isWxBrowser } from '@/utils'
import { initHanddrawBgmusic, playHanddrawBgmusic, pauseHanddrawBgmusic } from '@/utils/audio'

export default {
  components: {
    Loading,
    Effect
  },
  data() {
    return {
      isShowLoading: true,
      isShowPic: false,
      isShow: false,
      ew: 1190,
      img: null,
      imgX: 0,
      imgY: 0,
      scale: 1,
      imgScale: 1.5, // 缩放比例
      maxScale: 1.05,
      minScale: 0.95,
      imgNaturalSize: 0, // 图片原始尺寸
      ovvMarkTypeObj: {},
      ovvId: null,
      pointObj: {
        w: 30,
        h: 30,
        type: 0
      },
      markerList: [],
      audio: null,
      isMute: true,
      isFinish: true,
      mouse: {x: 0, y: 0},
      downX: 0,
      downY: 0,
      mousePosition: {
        isDrag: false,
        x: 0,
        y: 0
      }
    }
  },
  computed: {
    ...mapGetters(['ovvData', 'loadInfo']),
    getLoadImage() {
      if (!this.loadInfo) return false
      if (this.ovvData) {
        if(isPc() && this.ovvData.load && this.ovvData.load.pc_load_img) {
          return this.ovvData.load.pc_load_img
        }
        if(isMobile() && this.ovvData.load && this.ovvData.load.load_img) {
          return this.ovvData.load.load_img
        }
      }
    },
    getOvvImage() {
      if (this.ovvData) {
        this.img = this.$refs.imgHook
        return $globalconfig.URLS.API + this.ovvData.imageurl
      }
    },
    getStartPic() {
      if (this.ovvData && this.ovvData.startpicurl) {
        let url = this.ovvData.startpicurl.indexOf('|') != -1 ? this.ovvData.startpicurl.split('|')[1] : this.ovvData
          .startpicurl
        return $globalconfig.URLS.API + url
      }
    },
    getMusic() {
      if (this.ovvData && this.ovvData.bgmusicurl) {
        // let url = this.ovvData.bgmusicurl.indexOf('|') != -1 ? this.ovvData.bgmusicurl.split('|')[1] : this.ovvData.bgmusicurl
        // return $globalconfig.URLS.API + url
        return this.ovvData.full_bgmusic_url
      }
    },
    isShowEffect() {
      if(this.ovvData) {
        return this.ovvData.bgeffect
      }
    }
  },
  created() {
    this.vw = document.documentElement.clientWidth
    this.vh = document.documentElement.clientHeight
    this.ovvMarkTypeObj = this.$CONFIG.ovvMarkType

    this.ovvId = this.$route.params.id
  },
  mounted() {
    // 如果不是微信浏览器
    if (!isWxBrowser()) {
      setTimeout(() => {
        initHanddrawBgmusic(this.ovvData.full_bgmusic_url)
      }, 3000)
    } else {
      // 初始化音频
      document.addEventListener('WeixinJSBridgeReady', () => {
        if (this.ovvData) {
          initHanddrawBgmusic(this.ovvData.full_bgmusic_url)
        } else {
          setTimeout(() => {
            initHanddrawBgmusic(this.ovvData.full_bgmusic_url || '')
          }, 500)
        }
      },false)
    }

    // 发送用户数据
    setTimeout(() => {
      //实例化城市查询类
      var cityData
      var userData = {
        sw: getViewport().VW,
        sh: getViewport().VH,
        ip: getIP(),
        city: '',
        region: '',
        type: getPlatform() ? 1 : 2,
        overview_id: this.ovvData ? this.ovvData.overview_id : '',
        userid: this.ovvData ? this.ovvData.user_id : '',
        type_id: 0,
      }

      try {
        let citysearch = new AMap.CitySearch()

        //自动获取用户IP，返回当前城市
        citysearch.getLocalCity((status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            cityData = result
            userData.city = cityData ? cityData.city : ''
            userData.region = cityData ? cityData.province : ''
            this.$store.dispatch('sendCustomInfoOvv', userData)
          }
        })
      } catch (e) {
        this.$store.dispatch('sendCustomInfoOvv', userData)
      }
    }, 5000)

  },
  methods: {
    loadImage() {
      if(this.getOvvImage) {
        var img = new Image()
        // this.img = img

        img.onload = () => {
          this.isShow = true
          this.$bar.finish()

          this.resizeImage()
          // this.loadBgMusic()

          setTimeout(() => {
            if(!this.getLoadImage) {
              this.isShowPic = true
              this.hideStartPic()
            }
          }, 1000)
        }
        img.src = this.getOvvImage

        img.onerror = () => {
          this.$vgo.tip('加载失败', 'error')
        }
      }
    },
    moveImage() {
      let step = this.imgY
      const move = () => {
        step += 12
        if(parseInt(this.img.style.top) > this.imgY / 4) {
          this.img.style.top = -step + 'px'
          timer = requestAnimationFrame(move)
        } else {
          this.loadMarkers()
          this.imgX = (this.vw - this.img.width * this.scale) / 2
          this.imgY = (this.vh - this.vw / (this.img.width / this.img.height) * this.scale) / 2
        }
      }
      cancelAnimationFrame(timer)
      var timer = requestAnimationFrame(move)
    },
    loadMarkers() {
      let tempArr = []
      if (this.ovvData && this.ovvData.point_list) {
        tempArr = DeepCloneData(this.ovvData.point_list)
      }
      tempArr.map(marker => {
        // 偏差修正
        marker.y = marker.y + 20
        this.addMarkers(marker)
      })
    },
    addMarkers(marker) {
      let self = this
      let _marker = document.createElement('div')
      let oSpan = document.createElement('span')
      let oImg = document.createElement('img')

      oSpan.innerHTML = marker.name || marker.pano_name
      oSpan.className = 'text omit'

      _marker.className = 'ovv-item pos-a'
      _marker.style.zIndex = 99

      _marker.setAttribute('id', marker.pano_id)
      this.setMarkerOffset(_marker, marker)

      // _marker.href = 'http://192.168.0.103:8082/#/panoview/' + marker.pano_id + '?ovv=' + self.ovvId
      // _marker.href = $globalconfig.URLS.PANO_VIEW_PREFIX + marker.pano_id + '?ovv=' + self.ovvId
      _marker.onclick = function() {
        // const url = '/panoview/' + marker.pano_id + '?ovv=' + self.ovvId + '&t=' + Date.now()
        // $VM.$router.push(url)
        const url = $globalconfig.URLS.PANO_VIEW_PREFIX + marker.pano_id + '?ovv=' + self.ovvId + '&t=' + Date.now()
        window.location.replace(url)
        setTimeout(() => {
          window.location.reload()
        }, 20)
      }


      oImg.src = this.ovvMarkTypeObj.imgs[this.ovvData.styletype + 1]
      if(this.ovvData.styletype > 0 && this.ovvData.styleeffect > 0) {
        oImg.className = `animated infinite ${this.ovvMarkTypeObj.effect[this.ovvData.styleeffect]}`
      }
      if(isMobile()) {
        oImg.style.width = this.pointObj.w + 'px'
        oImg.style.height = this.pointObj.h + 'px'
      } else {
        oImg.style.width = this.pointObj.w + 'px'
        oImg.style.height = this.pointObj.h + 'px'
      }
      oImg.style.marginLeft = -this.pointObj.w / 2 + 'px'
      _marker.appendChild(oImg)
      _marker.appendChild(oSpan)

      this.markerList.push({
        marker: _marker,
        param: marker
      })

      this.$refs.imgWrap.appendChild(_marker)
      return _marker
    },
    reloadMarkers() {
      this.markerList.map((el, index) => {
        this.setMarkerOffset(el.marker, el.param, {x: el.param.x, y: el.param.y})
      })
    },
    setMarkerOffset(marker, position) {
      let offset = this.getImagePos()
      let eh = this.ovvData.imageheight / (this.ovvData.imagewidth / this.ew)

      let l = parseInt(this.img.width * (position.x / this.ew)+ offset.left + this.pointObj.w/2)
      let t = parseInt(this.img.height * (position.y / eh) + offset.top - this.pointObj.w)

      marker.style.left = l + 'px'
      marker.style.top =  t + 'px'

      this.isFinish = true
    },
    playMusic() {
      playHanddrawBgmusic()
    },
    pauseMusic() {
      pauseHanddrawBgmusic()
    },
    toggleMusic() {
      if (this.isMute) {
        pauseHanddrawBgmusic()
      } else {
        playHanddrawBgmusic()
      }
      this.isMute = !this.isMute
    },
    // playMusic() {
    //   let au = this.$refs.ovvAudio
    //   au.play()
    //   // if(this.audio && this.audio.src) {
    //   //   this.audio.play()
    //   // }
    // },
    // pauseMusic() {
    //   let au = this.$refs.ovvAudio
    //   au.pause()
    //   // if(this.audio && this.audio.src) {
    //   //   this.audio.pause()
    //   // }
    // },
    // toggleMusic() {
    //   let au = this.$refs.ovvAudio
    //   // this.isMute ? this.audio.pause() : this.audio.play()
    //   this.isMute ? au.pause() : au.play()
    //   this.isMute = !this.isMute
    // },
    loadBgMusic() {
      if(!this.getMusic) return
      if(!this.audio) {
        let au = document.createElement("audio")
        au.setAttribute('src', this.getMusic)
        au.loop = true
        au.src = this.getMusic
        this.audio = au
        document.body.appendChild(au)
      }
    },
    hideStartPic(isClick) {
      if(isClick) {
        this.isShowPic = false
        this.playMusic()
        return
      }
      let num = 3
      let timer
      const countdown = () => {
        timer = setTimeout(() => {
          if(num > 0) {
            num--
            countdown()
          } else {
            clearTimeout(timer)
            this.isShowPic = false
            this.playMusic()
          }
        }, 1000)
      }
      countdown()
    },
    closeLoading() {
      this.isShowLoading = false
      setTimeout(() => {
        this.isShowPic = true
        this.hideStartPic()
      }, 3000)
    },
    getStyle(el, name) {
      return getComputedStyle(el)[name]
    },
    getImageDim() {
      let w0 = this.img.width
      let h0 = this.img.height
      return {
        w: w0,
        h: h0
      }
    },
    getImagePos() {
      let left = parseFloat(this.getStyle(this.img, 'left'))
      let top = parseFloat(this.getStyle(this.img, 'top'))

      return {
        left,
        top
      }
    }
  },
  beforeDestroy () {
    this.pauseMusic()
    this.audio = null
  }
}
